<?php
/*
 * @Description    : 短信发送
 * @Author         : QianLong
 * @Date           : 2023-01-11 12:13:55
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2024-05-09 17:48:46
 */

declare(strict_types=1);

namespace App\Controller;

use App\Common\RedisCache;
use App\Constants\Status;
use App\Exception\ApiException;
use App\Job\SignFailAddJob;
use App\Job\SmsDataPreJob;
use Qianlong\Validate\Validate;

class SmsController extends AbstractController
{
  public function send()
  {
    $valitor = new Validate();
    $valitor->addColumn('ss_id')->required();
    $valitor->addColumn('st_id')->required();
    $valitor->addColumn('params_json')->optional();
    $valitor->addColumn('client_ip')->optional();
    $valitor->addColumn('phone')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $phoneList = explode(',', $param['phone']);
    $userInfo = $this->dataResource->getUserInfo();
    $redisCache = new RedisCache;
    $emailSetting = $redisCache->getSmsSetting($userInfo['uid']);
    $remoteIp = $this->dataResource->getClientIp($this->request);
    if ($emailSetting['ip_limit'] == 1 && !empty($emailSetting['server_ip'])) {
      $sysSetting = $redisCache->getSysSetting();
      $allIp = $sysSetting['server_ip'].','. $emailSetting['server_ip'];
      $server_ip = explode(',', $allIp);
      $is_local = filter_var($remoteIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
      if (!in_array($remoteIp, $server_ip) && $is_local != false) {
        return $this->response->json(Status::CODE_FAIL, 'IP不在可信范围内', []);
      }
    }
    if (count($phoneList) > 1000) {
      return $this->response->json(Status::CODE_FAIL, '单次最多可传入1000个手机号', []);
    }
    if (isset($param['is_filter']) && $param['is_filter'] == 1 && empty($param['filter_id'])) {
      return $this->response->json(Status::CODE_FAIL, '开启过滤后，filter_id为必填项', []);
    }
    $serverInfo = $redisCache->getSmsServer($param['ss_id']);
    $newSign = (new \App\Service\Common)->devSignGeneral($param, $serverInfo['server_secret']);
    $newSign2 = (new \App\Service\Common)->generateSignature($param, $serverInfo['server_secret']);
    if ($param['sign'] != $newSign && $param['sign'] != $newSign2['sign']) {
      $logData['url'] = $this->request->fullUrl();
      $logData['remoteIp'] = $remoteIp;
      $logData['user_sign'] = $param['sign'];
      $logData['server_sign'] = $newSign2['sign'];
      $logData['server_query'] = $newSign2['query'];
      $logData['uid'] = $serverInfo['uid'];
      queue_push(new SignFailAddJob($logData));
      return $this->response->json(Status::CODE_FAIL, 'sign签名校验失败');
    }
    if ($serverInfo['status'] != 1) {
      return $this->response->json(Status::CODE_FAIL, '当前配置状态不可用，如需使用，请登录柠聚开发平台启用后重试', []);
    }
    $param['uid'] = (int)$userInfo['uid'];
    $param['client_ip'] = (!isset($param['client_ip']) || empty($param['client_ip']))?$remoteIp: $param['client_ip'];
    queue_push(new SmsDataPreJob($param));
    return $this->response->json(Status::CODE_OK, '任务下发成功，请稍后查看发送日志', []);
  }
  public function aliyunSmsReport()
  {
    $param = $this->request->all();
    // $file = BASE_PATH . '/runtime/aliyunSmsReport.txt';
    // file_put_contents($file, json_encode($param)."\r\n",FILE_APPEND);
  }
  public function aliyunSmsUp()
  {
    $param = $this->request->all();
    // $file = BASE_PATH . '/runtime/aliyunSmsUp.txt';
    // file_put_contents($file, json_encode($param) . "\r\n",FILE_APPEND);
  }
  public function getCate()
  {
    $valitor = new Validate();
    $valitor->addColumn('cate_id')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $where['cate_id'] = $param['cate_id'];
    $where['status'] = 1;
    $hasLog = mongodb2()->sms_tpl_list->find($where);
    $returnD = [];
    foreach ($hasLog as $key => $vo) {
      $item['_id'] = $vo['_id'];
      $item['title'] = $vo['title'];
      $returnD[] = $item;
    }
    return $this->response->json(Status::CODE_OK, 'success', $returnD);
  }
}
